﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyUtils
{
	public sealed class WeakDelegate<T> where T : class
	{
		// todo do not use WeakEventHandler. Lets create more efficient mechanism
		readonly List<WeakEventHandler<T>> _list = new List<WeakEventHandler<T>>();

		public void Subscribe(T deleg)
		{
			lock (_list)
			{
				_list.Add(new WeakEventHandler<T>((Delegate)(object)deleg));
			}
		}

		public void Unsubscribe(T value)
		{
			var del = (Delegate)(object)value;
			var mi = del.Method;
			lock (_list)
			{
				_list.RemoveAll(x => x.MethodInfo == mi);
			}
		}

		public void Invoke()
		{
			//_s
//			WeakEventHandler<T>[] toRun;
//			lock (_list)
//			{
//				toRun = _list.ToArray();
//			}
//			foreach (var weakEventHandler in toRun)
//			{
//				weakEventHandler.
//			}
		}
	}
}
